import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../controller/userController.dart';
import '../model/user_entity.dart';
import '../widget/CustomDrawer.dart';
import '../widget/GoodsGridView.dart';
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  UserController userController = Get.find<UserController>();
  late Rx<UserEntity> user = userController.user;
  
  final orderTypes = [
    {'type': 1, 'text': '待付款', 'icon': Icons.attach_money_outlined},
    {'type': 2, 'text': '待发货', 'icon': Icons.access_time_outlined},
    {'type': 3, 'text': '待收货', 'icon': Icons.local_shipping_outlined},
    {'type': 4, 'text': '待评价', 'icon': Icons.comment},
  ];

  List<Widget> _buildOrderTypes() {
    List<Widget> temp = [];
    for (var type in orderTypes) {
        temp.add(
          GestureDetector(
            onTap: (){
              print(type);
              Get.toNamed('/orderList',arguments: {"initIndex":type["type"]});
            },
            child: Column(
              children: [
                Icon(type["icon"] as IconData?,color: Colors.orange,),
                Text(
                  type["text"].toString(),
                  style: TextStyle(fontSize: 10),
                )
              ],
            ),
          )
        );
    }
    return temp;
  }

  Future<void> _initUser() async {
    await userController.updateUser();
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _initUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      endDrawer: const CustomDrawer(),
      drawerEnableOpenDragGesture: true, //作用：允许手势滑动打开抽屉
      appBar: AppBar
        (
          title: const Text('个人主页'),
          centerTitle: true,
          actions: [
            Builder(
              builder: (context) {
                return IconButton(
                    icon: Icon(Icons.settings),
                    onPressed: () {
                      Scaffold.of(context).openEndDrawer();  // 使用 Builder 生成的 context
                    }
                );
              },
            ),
        ],
      ),
      body: SafeArea(
        child:Obx(() =>  Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          color: const Color.fromRGBO(235, 235, 235, 1),
          child: ListView(
            children: [
              Container(
                decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: NetworkImage("https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/center_bg.png"),
                      fit: BoxFit.cover
                  ),
                ),
                width:MediaQuery.of(context).size.width, // 第一层容器的宽度
                height: MediaQuery.of(context).size.height * 0.3, // 第一层容器的高度
                child: Stack(
                  clipBehavior: Clip.none, // 允许子组件超出父组件的边界
                  children: [
                    Positioned(
                      top: MediaQuery.of(context).size.height * 0.25 * 0.25,
                      child: Container(
                          height: 80,
                          width: MediaQuery.of(context).size.width,
                          child:
                          ListTile(
                              leading: CircleAvatar(backgroundImage:
                              user.value.id>0?
                              NetworkImage(user.value.userAvatar):
                              NetworkImage("https://www.shijuepi.com/uploads/allimg/201118/1-20111Q63612.jpg"),
                              ),
                              title: Text(user.value.id>0?user.value.userName:"未登录",style: TextStyle(color: Colors.white,fontSize: 12,fontWeight: FontWeight.w400),),
                              trailing: TextButton(
                                onPressed: () async {
                                  if(user.value.id>0){
                                    await userController.logout();
                                  }
                                  //跳转登陆页面
                                  Get.toNamed("/login");
                                },
                                child: Text(user.value.id>0?"退出登录":"登录",style: TextStyle(color: Colors.white),),

                              )
                          )),
                    )
                    ,
                    Positioned(
                        left: (MediaQuery.of(context).size.width - MediaQuery.of(context).size.width * 0.8) / 2.25, // 居中的关键
                        top: MediaQuery.of(context).size.height * 0.25 * 0.7, // 第一层容器高度的一半减去第二层容器高度的一半
                        child: Container(
                          //设计圆角
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(3),
                              color: Colors.white,
                            ),
                            width: MediaQuery.of(context).size.width * 0.8, // 第一层容器的 90%
                            height: MediaQuery.of(context).size.width * 0.25,
                            child: Column(
                              children: [
                                const ListTile(
                                  title: Text("我的订单",style: TextStyle(fontSize: 12),),
                                  trailing:Text("全部订单>",style: TextStyle(fontSize: 12,color: Colors.black45),),
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  children: _buildOrderTypes(),
                                )
                              ],
                            )
                        )
                    ),
                  ],
                ),
              ),
              SizedBox(height: 30,),
              //商品展示区
              const GoodsGridView()
            ],
          ),
        )))
      );
  }
}
